//
//  GridView.m
//  ATNetworks
//
//  Created by Ankit Thakur on 18/04/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "GridView.h"

#import "IconView.h"

#import "ATImageDownloader.h"


@implementation GridView

@synthesize imageUrlArray;
@synthesize imageArray;
@synthesize imageDownloader;
@synthesize labelArray;
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
		
		imageUrlArray = [[NSMutableArray arrayWithObjects:
						  @"http://t1.gstatic.com/images?q=tbn:JJcFsrX-VhLDyM:http://www.anvari.org/db/cols/Persian_Models/Persian_Models_VS.jpg",
						  
						  @"http://t2.gstatic.com/images?q=tbn:YWNavZYMmY41XM:http://earth2tech.files.wordpress.com/2009/06/tesla-models.jpg",
						  
						  @"http://www.yosax.com/wp-content/uploads/proton-in-india.jpg",
						  
						  @"http://www.dieselstation.com/pics/Spyker%20C12%20Zagato-car-wallpaper.jpg",
						  
						  @"http://cdn-www.rsportscars.com/images/ferrari/2006-ferrari-f430-challenge/f430ch06_011600_w800.jpg",
						  
						  @"http://www.jackzap.com/wp-content/uploads/2009/07/ferrari_california-8891.jpg",
						  
						  @"http://www.dieselstation.com/wallpapers/thumbnails/Spyker/C12-Zagato/SMALL_Spyker%20C12%20Zagato-widescreen-04.jpg",
						  
						  @"http://www.dieselstation.com/wallpapers/thumbnails/Spyker/C12-Zagato/SMALL_Spyker%20C12%20Zagato-widescreen-05.jpg",nil] retain];
		
    }
    return self;
}


- (void)drawRect:(CGRect)rect {
		// Drawing code
	[self performSelectorInBackground:@selector(loadIconImage) withObject:nil];
	[self performSelector:@selector(createIconView)];
}

- (NSInteger) numberOfIcons{
	
	return [imageUrlArray count];
}



-(void) createIconView{
	
	CGRect rect = self.bounds;
	UIView *_headerView = [[UIView alloc] initWithFrame:CGRectMake(rect.origin.x, 
																   rect.origin.y, 
																   rect.size.width, 
																   200)];
	
	int index = 1;
	
	
	for (int row = 0; row <ICON_ROWS; row++) {
		for (int col=0; col < ICON_COLUMNS; col++) {
			CGRect rect = CGRectMake(ICON_MARGIN*col+ICON_WIDTH*col-ICON_WIDTH*1, ICON_MARGIN*row + ICON_HEIGHT*row-ICON_HEIGHT*1, ICON_WIDTH, ICON_HEIGHT);
			CGRect frame = CGRectMake(SIDE_MARGIN + col * (ICON_MARGIN + ICON_WIDTH),
                                      ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT),
                                      ICON_WIDTH, 
									  ICON_HEIGHT);
			
            CGRect labelFrame = CGRectMake(SIDE_MARGIN + col * (ICON_MARGIN + ICON_WIDTH),
										   ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT)+ICON_HEIGHT,
										   ICON_LABEL_WIDTH, 
										   ICON_MARGIN);
            
            
			
            IconView *icon = [[[IconView alloc] initWithFrame:frame] autorelease];
			[icon setTag:index];
			[icon addTarget:delegate action:@selector(fobAction:) forControlEvents:UIControlEventTouchUpInside];
			NSLog(@"%@", icon);
			[_headerView addSubview:icon];
			
				// Setting the fob name
			if(index-1 < [labelArray count]){
				
				UILabel *label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
				
				[label setText:[labelArray objectAtIndex:index-1]];
				label.numberOfLines = 2;
				label.font = kFontNormal;
				label.textAlignment = UITextAlignmentCenter;
				label.backgroundColor = kColorClear;
				label.adjustsFontSizeToFitWidth = YES;
				[_headerView addSubview:label];
			}
			
			
			index++;
			
			_headerView.frame = CGRectMake(rect.origin.x, 
										   rect.origin.y, 
										   rect.size.width, 
										   ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT)+ ICON_HEIGHT);
			
		}
	}
	
	
	for (int col=0; col < LAST_ROW_ICONS; col++) {
		int row = ICON_ROWS;
		CGRect rect = CGRectMake(ICON_MARGIN*col+ICON_WIDTH*col-ICON_WIDTH*1, ICON_MARGIN*row + ICON_HEIGHT*row-ICON_HEIGHT*1, ICON_WIDTH, ICON_HEIGHT);
		CGRect frame = CGRectMake(SIDE_MARGIN + col * (ICON_MARGIN + ICON_WIDTH),
								  ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT),
								  ICON_WIDTH, 
								  ICON_HEIGHT);
		
		CGRect labelFrame = CGRectMake(SIDE_MARGIN + col * (ICON_MARGIN + ICON_WIDTH),
									   ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT)+ICON_MARGIN,
									   ICON_WIDTH, 
									   ICON_MARGIN);
		
		IconView *icon = [[[IconView alloc] initWithFrame:frame] autorelease];
		[icon setTag:index];
		[icon addTarget:delegate action:@selector(fobAction:) forControlEvents:UIControlEventTouchUpInside];
		[_headerView addSubview:icon];
		
			// Setting the fob name
		if(index-1 < [labelArray count]){
			UILabel *label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
			label.font = kFontNormal;
			label.textAlignment = UITextAlignmentCenter;
			label.backgroundColor = kColorClear;
			label.adjustsFontSizeToFitWidth = YES;
			
			
			[label setText:[labelArray objectAtIndex:index-1]];
			label.numberOfLines = 2;
			[_headerView addSubview:label];
		}
		
		
		index++;
		
		_headerView.frame = CGRectMake(rect.origin.x, 
									   rect.origin.y, 
									   rect.size.width, 
									   ICON_MARGIN + row * (ICON_MARGIN + ICON_HEIGHT)+ ICON_HEIGHT);
		
	}
	
	
	
	UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(rect.origin.x, 
																			  rect.origin.y, 
																			  rect.size.width, 
																			  rect.size.height)];
	scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	
	
	_headerView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	scrollView.contentSize = CGSizeMake(_headerView.bounds.size.width, _headerView.bounds.size.height+300) ;
	
	CGRect rect1 = _headerView.frame;
	_headerView.frame = CGRectMake(0, 0, 320, rect1.size.height);
	scrollView.bounces = YES;
	scrollView.bouncesZoom = YES;
	scrollView.scrollEnabled = YES;
	scrollView.minimumZoomScale = 0.5;
	scrollView.maximumZoomScale = 5.0;
	scrollView.delegate = nil;
	scrollView.tag = SCROLLVIEW_TAG;
	[scrollView addSubview: _headerView];
	[self addSubview:scrollView];
	
	[scrollView release];
	scrollView = nil;
	[_headerView release];
	_headerView = nil;
	
	
}

-(void) loadIconImage{
	
	NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
	@try {
		if (imageDownloader==nil)
			imageDownloader = [[ATImageDownloader alloc] init];
		
		for (int i = 1; i < [imageUrlArray count]+1; i++) {
			
			NSString *imageUrlString = [imageUrlArray objectAtIndex:i-1];
			NSURL *url = [[NSURL alloc] initWithString:imageUrlString];
			NSString *tag = [NSString stringWithFormat:@"%d",i];
			NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:url,@"url",tag,@"tag",nil];
			[imageDownloader loadImageFromURL:dict withCallbackTarget:self withCallbackSelector:@selector(callBack:)];
			tag = nil;
			dict = nil;
			[url release];
			url = nil;
		}
		
	}
	@catch (NSException * e) {
		logger(@"loadIconImage ---> %@",[e description]);
	}
	
	
	[subPool release];
}

- (void) callBack: (NSMutableDictionary*)dict_
{
	int tag_ = [[dict_ objectForKey:@"tag"] intValue];
	[(IconView*)[[[self viewWithTag:SCROLLVIEW_TAG] viewWithTag:tag_] viewWithTag:222] removeFromSuperview];
	[(IconView*)[[self viewWithTag:SCROLLVIEW_TAG] viewWithTag:tag_] setBackgroundImage:[dict_ objectForKey:@"imageData"] forState:UIControlStateNormal];
	dict_ = nil;
	
}
- (void)dealloc {
	[imageUrlArray release];
	imageUrlArray = nil;
	if (imageDownloader != nil)
		[imageDownloader release];
	imageDownloader = nil;
    [super dealloc];
}


@end